package com.wanpinghui.supplier.widgets;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/11/21
 ***/

public class CodeCountDownTextView extends AppCompatTextView {
    private int countDownL;
    private Subscription mSubscription;

    public CodeCountDownTextView(Context context) {
        super(context);
    }

    public CodeCountDownTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CodeCountDownTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void startCountDown() {
        setEnabled(false);
        countDownL = 60;
        if (mSubscription == null || mSubscription.isUnsubscribed()) {
            mSubscription = Observable.interval(1000, 1000, TimeUnit.MILLISECONDS, Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            countDownL--;
                            if (countDownL == 0) {
                                resetCountDown();
                            } else {
                                setText(countDownL + "s后重新获取");
                            }
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                        }
                    });
        }
    }

    private void resetCountDown() {
        setEnabled(true);
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
        setText("获取验证码");
        countDownL = 60;
    }

    public void stop() {
        resetCountDown();
    }
}
